#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int, int> pii;
const int N = 1010;
int m, n;
char a[N][N];
int b[4][N][N];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
void bfs(int num)
{
	memset(b[num], -1, sizeof(b[num]));
	deque<pii> as;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (a[i][j] - '0' == num)
			{
				b[num][i][j] = 0;
				as.push_front({ i,j });
			}
		}
	}
	while (as.size())
	{
		auto e = as.front();
		int x = e.first;
		int y = e.second;
		as.pop_front();
		for (int k = 0; k < 4; k++)
		{
			int x1 = x + dx[k];
			int y1 = y + dy[k];
			if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && a[x1][y1] != '#')
			{
				int w = (a[x1][y1] == '.' ? 1 : 0);
				if (b[num][x1][y1] == -1)
				{
					b[num][x1][y1] = b[num][x][y] + w;
					if (w)
					{
						as.push_back({ x1,y1 });
					}
					else
					{
						as.push_front({ x1,y1 });
					}
				}
				else if (b[num][x][y] + w < b[num][x1][y1])
				{
					b[num][x1][y1] = b[num][x][y] + w;
				}
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			cin >> a[i][j];
		}
	}
	bfs(1);
	bfs(2);
	bfs(3);
	int ret = 0x3f3f3f3f;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (a[i][j] == '#')
			{
				continue;
			}
			int z = b[1][i][j];
			int x = b[2][i][j];
			int c = b[3][i][j];
			if (z == -1 || x == -1 || c == -1)
			{
				continue;
			}
			if (a[i][j] == '.')
			{
				ret = min(ret, z + x + c - 2);
			}
			else
			{
				ret = min(ret, z + x + c);
			}
		}
	}
	if (ret == 0x3f3f3f3f)
	{
		cout << -1 << endl;
	}
	else
		cout << ret << endl;
	return 0;
}